package com.code.demo.ui;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import com.code.demo.R;
import com.code.demo.service.MyService;

/**
 * Created by android on 2018/11/30.
 */

public class ServiceActivity extends AppCompatActivity {

    private MyService.MyBinder binder;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service);
    }

    public void onStartService(View view) {
        Intent intent = new Intent(this, MyService.class);
        startService(intent);
        Log.e("TagService", "startService");
    }

    public void onStopService(View view) {
        Intent intent = new Intent(this, MyService.class);
        stopService(intent);
        Log.e("TagService", "stopService");
    }

    public void onBindService(View view) {
        Intent intent = new Intent(this, MyService.class);
        bindService(intent, connection, BIND_AUTO_CREATE);
        Log.e("TagService", "bindService");
    }

    public void onUnbindService(View view) {
        unbindService(connection);
        Log.e("TagService", "onUnbindService");
    }

    public void onGetCount(View view) {
        Log.e("TagService", "onGetCount");
        binder.getCount();
    }

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e("TagService", "onServiceConnected name is "+name.toString());

            binder = (MyService.MyBinder) service;

            binder.startCount();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e("TagService", "onServiceDisconnected name is "+name.toString());
        }
    };
}
